class CensorController < ApplicationController

  def cancel
    result = Result.find(params[:result_id])

    # pending two fingers
    finger1 = Finger.find(result.finger1_id)
    finger2 = Finger.find(result.finger2_id)
    finger1.reset
    finger2.reset

    redirect_to :back
  end

  def solve
    sample1 = Sample.find(params[:sample1_id])
    sample2 = Sample.find(params[:sample2_id])
    task = Task.find(params[:task_id])
    r = params[:answer]

    result = Result.where(sample1_id: sample1.id, sample2_id: sample2.id, task_id: task.id).first
    if result != nil
      redirect_to censor_task_path(task)
      return
    end
    result = nil

    if r == 'DISCARD'
      result = Result.new(sample1_id: sample1.id, sample2_id: sample2.id,
        finger1_id: sample1.finger_id, finger2_id: sample2.finger_id, marker: 'no')
      sample1.finger.update_attributes(marker: 'invalid')
      redirect_to censor_task_path(task)
      return
    end

    if r == 'YES'
      result = Result.new(sample1_id: sample1.id, sample2_id: sample2.id,
        finger1_id: sample1.finger_id, finger2_id: sample2.finger_id, marker: 'yes')
    else
      result = Result.new(sample1_id: sample1.id, sample2_id: sample2.id,
        finger1_id: sample1.finger_id, finger2_id: sample2.finger_id, marker: 'no')
    end
    task.results.push result

    # Inter match
    if sample1.finger_id != sample2.finger_id
      if r == 'NO'
        # Check if finger has been valid
        if sample1.finger.valid_sample_ids.size >= task.num_of_samples && 
           sample1.finger.matched_finger_ids.size >= task.valid_finger_ids.size
          puts "Add valid finger"
          sample1.finger.update_attributes(marker: 'valid')
        end
      else
        sample1.finger.update_attributes(marker: 'suspect')
      end
    else
    # Inner match
      if r == 'NO'
        if sample1.finger.samples.size - sample1.finger.invalid_sample_ids.size < task.num_of_samples
          sample1.finger.update_attributes(marker: 'invalid')
        end
      else
        #if task.fingers.valid.size == 0 && sample1.finger.valid_sample_ids.size >= task.num_of_samples
        if sample1.finger.valid_sample_ids.size >= task.num_of_samples
          sample1.finger.update_attributes(marker: 'valid')
        end
      end
    end

    if task.finished?
      redirect_to task_path(task)
    else
      redirect_to censor_task_path(task)
    end
  end
end
